package com.jichaoyun.config;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.jichaoyun.sys.interceptor.JWTInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zhen
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

  @Bean
  public CorsFilter corsFilter(){
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.addAllowedOriginPattern("*");//添加允许访问的前端地址
//    configuration.addAllowedOrigin("*"); //这里填写请求的前端服务器
    configuration.setAllowCredentials(true);//允许传入cookie
    configuration.addAllowedMethod("*");//允许哪些方法，比如说get，put，post，这里允许全部
    configuration.addAllowedHeader("*");//允许所有的请求头过来

    UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",configuration);//pattern允许拦截所有的东西进行审查

    return  new CorsFilter(urlBasedCorsConfigurationSource);
  }

  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQL_SERVER));
    return interceptor;
  }

  @Value("${web.upload-path}")
  private String uploadPath;

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadPath);
  }

  /**
   * 注册拦截器
   * */
  @Override
  public void addInterceptors(InterceptorRegistry registry){
    registry.addInterceptor(new JWTInterceptor())
        .addPathPatterns("/**")
            //拦截的地址
        .excludePathPatterns("/sys/user/login",
                              "/images/**",
                              "/error",
                              "/swagger-ui/**",
                              "/swagger-resources/**",
                              "/v3/**"
                );
  }
}
